import json
from json import JSONDecodeError

from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
from django.shortcuts import render, redirect
from .models import Taskdata, Task, users


# Create your views here.
def index(request, task_id):
    if not request.session.get('account'):
        staue = 'login'
    else:
        staue = 'logout'
    user_list = {i.user_account: [i.user_name, i.user_id] for i in users.objects.all()}
    if not request.session.get("account"):
        name = '请登录'
    else:
        name = user_list[request.session.get('account')][0]
    user_id = user_list[request.session.get('account')][1]
    task = Task.objects.get(id=task_id)
    # 从数据库中获取任务数据
    taskdatas = Taskdata.objects.filter(taskdata_task_id=task_id ,taskdata_assign=user_id)

    for index, taskdata in enumerate(taskdatas):
        taskdatas[index].taskdata_result = eval(taskdata.taskdata_result)

    item = request.GET.get('search')
    if not item:
        return render(request, 'annotating_data/index.html', {'taskdatas': taskdatas, 'task': task ,'name': name, 'staues': staue})
    else:
        task_list = Task.objects.filter(task_name__icontains=item)
        return render(request, 'task_market/all_grid.html', {'tasks': task_list, 'name': name, 'staues': staue})


def annotate(request, task_id, taskdata_id):
    if not request.session.get('account'):
        staue = 'login'
    else:
        staue = 'logout'
    user_list = {i.user_account: [i.user_name, i.user_id] for i in users.objects.all()}
    if not request.session.get("account"):
        name = '请登录'
    else:
        name = user_list[request.session.get('account')][0]
    user_id = user_list[request.session.get('account')][1]
    task = Task.objects.get(id=task_id)
    assign_data_all = Taskdata.objects.filter(taskdata_assign=user_id,taskdata_task_id=task_id).count()
    assign_data_anno = Taskdata.objects.filter(taskdata_assign=user_id,taskdata_task_id=task_id,taskdata_status='1').count()
    print(type(assign_data_all))
    perc_anno = str(assign_data_anno/assign_data_all*100)[:5]+'%'
    # for assign_data in assign_data_all:
    #     if assign_data.taskdata_result['']
    data_current = Taskdata.objects.get(taskdata_id=taskdata_id,taskdata_task_id=task_id)
    # data_assign_id = data_current.taskdata_assign  # 有权限查看的标注者id
    for index, data in enumerate(Taskdata.objects.filter(taskdata_assign=user_id, taskdata_task_id=task_id)):
        if data.taskdata_id == data_current.taskdata_id:
            if index == 0:
                pre_data = Taskdata.objects.filter(taskdata_assign=user_id, taskdata_task_id=task_id)[
                    len(Taskdata.objects.filter(taskdata_assign=user_id, taskdata_task_id=task_id)) - 1]
            else:
                pre_data = Taskdata.objects.filter(taskdata_assign=user_id, taskdata_task_id=task_id)[index - 1]
            if index == len(Taskdata.objects.filter(taskdata_assign=user_id, taskdata_task_id=task_id)) - 1:
                next_data = Taskdata.objects.filter(taskdata_assign=user_id, taskdata_task_id=task_id)[0]
            else:
                next_data = Taskdata.objects.filter(taskdata_assign=user_id, taskdata_task_id=task_id)[index + 1]

    # print(task.task_settings)
    task.task_settings = eval(task.task_settings)

    data_current.taskdata_result = eval(data_current.taskdata_result)

    item = request.GET.get('search')
    if not item:
        print(user_id, '###', data_current.taskdata_assign)
        print(data_current.taskdata_id)
        print(task.id)
        print(task.task_type)
        if user_id == data_current.taskdata_assign:

            # task.task_type = '5'  # 测试页面5
            print('######### annotating_data/annotate_{}.html #########'.format(task.task_type))
            return render(request, 'annotating_data/annotate_{}.html'.format(task.task_type),
                          {'data_current': data_current,  # 当前数据
                           'task': task,  # 当前任务
                           'pre_data': pre_data,  # 上一条数据
                           'next_data': next_data,  # 下一条数据
                           'name': name,
                           'staues': staue,
                           'all_assign_num':assign_data_all,
                           'anno_assign_num':assign_data_anno,
                           'perc_anno':perc_anno
                           })
        else:
            return render(request, 'annotating_data/404.html', {'name': name, 'staues': staue})
    else:
        task_list = Task.objects.filter(task_name__icontains=item)
        return render(request, 'task_market/all_grid.html', {'tasks': task_list, 'name': name, 'staues': staue})


def submit(request):
    print(request.POST.dict())
    type = request.POST.dict()['type']
    task_id = request.POST.dict()['task_id']
    next_data_id = request.POST.dict()['next_data_id']
    current_data_id = request.POST.dict()['current_data_id']
    # print('type',type)
    result = {}
    if type == '1' or type == '4':  # 文本分类和图片分类
        label = request.POST.dict()['label']
        result['label'] = label
        print(result)

    taskdata = Taskdata.objects.get(taskdata_id=current_data_id,taskdata_task_id=task_id)
    taskdata.taskdata_result = str(result)
    taskdata.taskdata_status = '1'
    taskdata.save()
    return redirect('annotating_data:annotate', task_id=task_id, taskdata_id=next_data_id)


def image_submit(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        result_from_js = data.get('result')
        # 构造result存储格式
        results = {}
        results['result'] = result_from_js
        taskdata_id = data.get('taskdata_id')
        taskdata = Taskdata.objects.get(taskdata_id = taskdata_id,taskdata_task_id = data.get('task_id'))
        taskdata.taskdata_result=results
        taskdata.taskdata_status = '1'
        taskdata.save()

        return HttpResponse(status=200)


def contact_config(labels):
    result = ''
    c = '<Label value="{}"></Label>'
    for label in labels:
        result = result + c.format(label)
    return result


def image_get(request):
    print(request.body)
    if request.method == 'POST':
        req = json.loads(request.body)

        task_id = req.get('task_id')
        taskdata_id = req.get('taskdata_id')

    taskdata = Taskdata.objects.get(taskdata_id=taskdata_id, taskdata_task_id=task_id)
    task = Task.objects.get(id=task_id)
    user_id = taskdata.taskdata_assign
    user = users.objects.get(user_id=user_id)
    labels = eval(task.task_settings)['labels']
    config_label = contact_config(labels)


    data = {
        'task': {
            'annotations': [ eval(taskdata.taskdata_result)], # 标记结果
            'id': int(taskdata_id),  # taskdata_id
            'data': {
                'image': 'http://localhost:8000/images/' + taskdata.taskdata_content  # taskdata_content
            }
        },
        'config': '''<View><Image name="img" value="$image"></Image>
       <RectangleLabels name="tag" toName="img" fillOpacity="0.5" strokeWidth="5">''' +
                  config_label
                  + ''' </RectangleLabels></View>''',
        'user': {
            'pk': 123,
            'firstName': user.user_name,
            'lastName': ""
        }
    }
    # print(data['task']['data']['image'])
    return JsonResponse(data)


# def image_submit(request):
#     if request.method == 'POST':
#         data = json.loads(request.body)
#         result = data.get('result')
#
#         print(result)
#         # 在这里处理传递过来的数据
#         # ...
#         return HttpResponse(status=200)
#
#
# def image_get(request):
#     if request.method == 'POST':
#         req = json.loads(request.body)
#         task_id = req.get('task_id')
#         taskdata_id = req.get('taskdata_id')
#
#     data = {
#         'task': {
#             'annotations': [
#                 {
#                     'id': "1001",
#                     'lead_time': 15.053,
#                     'result': [
#                         {
#                             'from_name': "tag",
#                             'id': "Dx_aB91ISN",
#                             'source': "$image",
#                             'to_name': "img",
#                             'type': "rectanglelabels",
#                             'value': {
#                                 'height': 10.458911419423693,
#                                 'rectanglelabels': [
#                                     "Moonwalker"
#                                 ],
#                                 'rotation': 0,
#                                 'width': 12.4,
#                                 'x': 50.8,
#                                 'y': 5.869797225186766
#                             }
#                         },
#                         {
#                             'from_name': "tag",
#                             'id': "Dx_aB91IS1",
#                             'source': "$image",
#                             'to_name': "img",
#                             'type': "rectanglelabels",
#                             'value': {
#                                 'height': 16.182572614107883,
#                                 'rectanglelabels': [
#                                     "Planet"
#                                 ],
#                                 'rotation': 0,
#                                 'width': 12.4,
#                                 'x': 50.8,
#                                 'y': 25.897225186766
#                             }
#
#                         }
#
#                     ]
#                 }
#             ],
#
#             'id': 1,
#             'data': {
#                 'image': ''
#                     # 'http://localhost:8000/images/wallhaven-l88zep_3840x2160.png'
#
#             }
#         },
#         'config': '''
#     <View>
#        <Image name="img" value="$image"></Image>
#        <RectangleLabels name="tag" toName="img" fillOpacity="0.5" strokeWidth="5">
#            <Label value="Planet"></Label>
#            <Label value="Moonwalker" background="red"></Label>
#            </RectangleLabels>
#     </View>
#        ''',
#         'user':{
#             'pk': 1,
#             'firstName': "James",
#             'lastName': "Dean"
#         }
#     }
#     return JsonResponse(data)
a = {
    'original_width': 3640,
    'original_height': 2048,
    'image_rotation': 0,
    'value': {
        'x': 50.8,
        'y': 5.869797225186766,
        'width': 12.4,
        'height': 10.458911419423693,
        'rotation': 0,
        'rectanglelabels': ['nose']},
    'id': 'Dx_aB91ISN',
    'from_name': 'tag',
    'to_name': 'img',
    'type': 'rectanglelabels',
    'origin': 'manual'},
b = {
    'original_width'
    :
        3640, 'original_height'
    :
        2048, 'image_rotation'
    :
        0, 'value'
    :
        {
            'x'
            :
                50.8, 'y'
        :
            25.897225186766, 'width'
        :
            12.4, 'height'
        :
            16.182572614107883, 'rotation'
        :
            0, 'rectanglelabels'
        :
            ['eye']
        }
    ,
    'id'
    :
        'Dx_aB91IS1', 'from_name'
    :
        'tag', 'to_name'
    :
        'img', 'type'
    :
        'rectanglelabels', 'origin'
    :
        'manual'
}
